package com.hooda.config;

import com.hooda.pojo.Configuration;
import com.hooda.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author zhangzp
 * @version 1.0, 2021/7/29
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.elements();
        for (Element element : list) {
            String id = element.attributeValue("id");

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setType(MappedStatement.SqlType.valueOf(element.getName()));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setSql(element.getTextTrim());

            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
